package test;

import common.Utils;
import org.openqa.selenium.By;

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.IOException;
import java.time.Duration;
import java.util.List;

public class QuestionManagePage extends Utils {
    public static String url = "http://dongliyang.online:10030/oj/layout/question";
    private String newTitle; // 用于存储新添加的题目标题
    public QuestionManagePage() throws IOException, InterruptedException {
        super(url);
    }

    // 测试 URL 是否正确
    public void testUrl() throws IOException {
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

        // 等待页面加载完成
        wait.until(ExpectedConditions.urlContains("/oj/layout/question"));
        assert driver.getCurrentUrl().equals(url) : "题目管理页面 URL 不正确";
        System.out.println("题目管理页面 URL 正确，当前 URL: " + driver.getCurrentUrl());
        getScreenShot("testUrl");
    }

    // 测试当前用户是否为“超级管理员”
    public void testCurrentUser() throws IOException {
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

        // 等待右上角用户元素加载
        WebElement userElement = wait.until(ExpectedConditions.presenceOfElementLocated(
                By.xpath("/html/body/div[1]/div/section/header/div/span/div")
        ));
        assert userElement.getText().equals("当前用户：超级管理员") : "当前用户不是超级管理员";
        System.out.println("当前用户显示正确：超级管理员");
        getScreenShot("testCurrentUser");
    }

    // 测试表格表头是否包含“题目ID”
    public void testTableHeader() throws IOException {
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

        // 等待表头加载
        WebElement headerElement = wait.until(ExpectedConditions.presenceOfElementLocated(
                By.xpath("/html/body/div[1]/div/section/main/div[2]/div[1]/div[1]/div[2]/table/thead/tr/th[1]/div")
        ));
        assert headerElement.getText().equals("题目ID") : "表格表头未包含‘题目ID’";
        System.out.println("表格表头包含‘题目ID’，显示正确。");
        getScreenShot("testTableHeader");
    }

    // 测试第一个题目的编辑
    public void testEditFirstQuestion() throws IOException {
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

        // 获取第一个题目的标题（编辑前）
        WebElement firstQuestionTitle = wait.until(ExpectedConditions.presenceOfElementLocated(
                By.xpath("/html/body/div[1]/div/section/main/div[2]/div[1]/div[1]/div[3]/div/div[1]/div/table/tbody/tr[1]/td[2]/div")
        ));
        String originalTitle = firstQuestionTitle.getText();
        System.out.println("第一个题目原始标题: " + originalTitle);

        // 点击第一个题目的“编辑”按钮
        WebElement editButton = wait.until(ExpectedConditions.elementToBeClickable(
                By.xpath("/html/body/div[1]/div/section/main/div[2]/div[1]/div[1]/div[3]/div/div[1]/div/table/tbody/tr[1]/td[6]/div/button[1]/span")
        ));
        editButton.click();

        // 等待编辑弹窗出现
        WebElement titleInput = wait.until(ExpectedConditions.elementToBeClickable(
                By.xpath("/html/body/div[1]/div/section/main/div[2]/div[3]/div/div/form/div[1]/div/div/div/input")
        ));

        // 修改题目标题
        String newTitle = "编辑后的题目_" + System.currentTimeMillis();
        titleInput.clear();
        titleInput.sendKeys(newTitle);

        // 点击“提交”按钮
        WebElement submitButton = wait.until(ExpectedConditions.elementToBeClickable(
                By.xpath("/html/body/div[1]/div/section/main/div[2]/div[3]/div/div/form/div[9]/div/button/span")
        ));
        submitButton.click();

        // 等待弹窗关闭并刷新页面
        wait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//button/span[text()='提交']")));
        driver.navigate().refresh();

        // 验证标题是否更新
        firstQuestionTitle = wait.until(ExpectedConditions.presenceOfElementLocated(
                By.xpath("/html/body/div[1]/div/section/main/div[2]/div[1]/div[1]/div[3]/div/div[1]/div/table/tbody/tr[1]/td[2]/div")
        ));
        assert firstQuestionTitle.getText().equals(newTitle) : "编辑题目失败，标题未更新";
        System.out.println("第一个题目编辑成功，新标题: " + newTitle);
        getScreenShot("testEditFirstQuestion");
    }

    // 测试删除新添加的题目
    public void testDeleteFirstQuestion() throws IOException {
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

        // 确保 newTitle 已设置（由 testAddQuestion 设置）
        if (newTitle == null) {
            throw new IllegalStateException("请先运行 testAddQuestion() 以添加新题目");
        }

        // 获取所有题目行
        List<WebElement> questionRows = wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(
                By.xpath("//table/tbody/tr")
        ));

        // 遍历题目，找到新添加的题目并删除
        boolean found = false;
        for (int i = 0; i < questionRows.size(); i++) {
            WebElement titleElement = questionRows.get(i).findElement(By.xpath("./td[2]/div"));
            if (titleElement.getText().equals(newTitle)) {
                System.out.println("找到新添加的题目，标题: " + newTitle);

                // 点击“删除”按钮
                WebElement deleteButton = questionRows.get(i).findElement(
                        By.xpath("./td[6]/div/button[2]/span")
                );
                deleteButton.click();

                // 等待页面刷新（保持您注释掉的确认弹窗逻辑）
                wait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//button/span[text()='确定']")));
                driver.navigate().refresh();

                // 验证题目是否被删除
                questionRows = wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(
                        By.xpath("//table/tbody/tr")
                ));
                boolean stillExists = false;
                for (WebElement row : questionRows) {
                    WebElement title = row.findElement(By.xpath("./td[2]/div"));
                    if (title.getText().equals(newTitle)) {
                        stillExists = true;
                        break;
                    }
                }
                assert !stillExists : "删除新添加的题目失败，题目仍存在";
                System.out.println("成功删除新添加的题目，标题: " + newTitle);
                getScreenShot("testDeleteFirstQuestion");
                found = true;
                break;
            }
        }

        if (!found) {
            throw new RuntimeException("未找到新添加的题目: " + newTitle);
        }
    }

    // 测试添加题目
    public void testAddQuestion() throws IOException, InterruptedException {
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

        // 点击“+ 添加题目”按钮
        WebElement addButton = wait.until(ExpectedConditions.elementToBeClickable(
                By.xpath("/html/body/div[1]/div/section/main/div[2]/form/div[3]/div/button[3]")
        ));
        addButton.click();

        // 等待添加弹窗出现
        WebElement titleInput = wait.until(ExpectedConditions.elementToBeClickable(
                By.xpath("/html/body/div[1]/div/section/main/div[2]/div[3]/div/div/form/div[1]/div/div/div/input")
        ));

        // 输入题目信息
        newTitle = "新题目_" + System.currentTimeMillis();
        titleInput.sendKeys(newTitle);



        try {
            // 1. 定位下拉框
            WebElement difficultySelectWrapper = wait.until(ExpectedConditions.presenceOfElementLocated(
                    By.xpath("/html/body/div[1]/div/section/main/div[2]/div[3]/div/div/form/div[2]/div/div/div/div[1]/div[2]")
            ));
            System.out.println("下拉框元素已找到: " + difficultySelectWrapper.getAttribute("outerHTML"));

            // 2. 定位下拉框的可点击区域（el-select__caret）
            WebElement difficultySelectCaret = wait.until(ExpectedConditions.elementToBeClickable(
                    By.xpath("/html/body/div[1]/div/section/main/div[2]/div[3]/div/div/form/div[2]/div/div/div")
            ));
            System.out.println("下拉框箭头元素已找到: " + difficultySelectCaret.getAttribute("outerHTML"));

            // 3. 使用鼠标点击下拉框，展开选项
            Actions actions = new Actions(driver);
            actions.moveToElement(difficultySelectCaret).click().perform();
            System.out.println("已使用鼠标点击下拉框，展开选项");

//            // 4. 等待选项列表可见
//            wait.until(ExpectedConditions.visibilityOfElementLocated(
//                    By.xpath("//div[contains(@class, 'el-select-dropdown')]")
//            ));

            // 5. 使用键盘操作选择“简单”（假设“简单”是第一个选项）
            // 按下 ↓ 键移动到“简单”，然后按 Enter 键确认
            actions.sendKeys(Keys.DOWN) // 移动到第一个选项（简单）
                    .sendKeys(Keys.ENTER) // 确认选择
                    .perform();
            System.out.println("已使用键盘操作选择‘简单’选项");

            // 6. 验证下拉框是否显示“简单”
            WebElement selectedDifficulty = wait.until(ExpectedConditions.presenceOfElementLocated(
                    By.xpath("//div[contains(@class, 'el-select__wrapper')]//span[text()='简单']")
            ));
            assert selectedDifficulty.isDisplayed() : "难度未正确选中为‘简单’";
            System.out.println("已成功选择难度：简单");

        } catch (Exception e) {
            System.out.println("操作下拉框失败: " + e.getMessage());
            System.out.println("页面源码: " + driver.getPageSource());
            getScreenShot("difficultySelect_failed");
            throw e;
        }

        // 输入时间限制（1000 毫秒）
        WebElement timeLimitInput = wait.until(ExpectedConditions.elementToBeClickable(
                By.xpath("/html/body/div[1]/div/section/main/div[2]/div[3]/div/div/form/div[3]/div/div/div/input")
        ));
        timeLimitInput.sendKeys("1000");
        System.out.println("已输入时间限制：1000 毫秒");

        // 输入空间限制（65536 字节）
        WebElement spaceLimitInput = wait.until(ExpectedConditions.elementToBeClickable(
                By.xpath("/html/body/div[1]/div/section/main/div[2]/div[3]/div/div/form/div[4]/div/div/div/input")
        ));
        spaceLimitInput.sendKeys("65536");
        System.out.println("已输入空间限制：65536 字节");

        // 输入题目内容（富文本编辑器）
        WebElement contentInput = wait.until(ExpectedConditions.elementToBeClickable(
                By.xpath("/html/body/div[1]/div/section/main/div[2]/div[3]/div/div/form/div[5]/div[2]/div/div[2]/div[1]/p")
        ));
        contentInput.sendKeys("请实现一个简单的加法程序");
        System.out.println("已输入题目内容：请实现一个简单的加法程序");

// 输入输入用例和输出用例（JSON 格式）
        WebElement inputCase = wait.until(ExpectedConditions.elementToBeClickable(
                By.xpath("/html/body/div[1]/div/section/main/div[2]/div[3]/div/div/form/div[6]/div/div/div/input")
        ));
        String jsonCases = "[{\"input\": \"5\\n12 788 2342281 345 8888888\", \"output\": \"Ou king=8888888 \\nJi queen=2342281 \"}, " +
                "{\"input\": \"2\\n2 3\", \"output\": \"Ou king=2 \\nJi queen=3 \"}, " +
                "{\"input\": \"3\\n4 6 7\", \"output\": \"Ou king=6 \\nJi queen=7 \"}, " +
                "{\"input\": \"4\\n1 3 5 7\", \"output\": \"Ou king=-1 \\nJi queen=7 \"}, " +
                "{\"input\": \"4\\n2 4 6 8\", \"output\": \"Ou king=8 \\nJi queen=-1 \"}]";
        inputCase.sendKeys(jsonCases);
        System.out.println("已输入用例（JSON 格式）：\n" + jsonCases);
// 输入测试代码（Ace 代码编辑器）
        WebElement codeEditor = wait.until(ExpectedConditions.presenceOfElementLocated(
                By.xpath("/html/body/div[1]/div/section/main/div[2]/div[3]/div/div/form/div[7]/div[2]/div")
        ));
        // 输入测试代码（Ace 代码编辑器）
        WebElement codeEditorMain = wait.until(ExpectedConditions.presenceOfElementLocated(
                By.xpath("/html/body/div[1]/div/section/main/div[2]/div[3]/div/div/form/div[8]/div[2]/div")
        ));
        // 输入代码（假设题目是 twoSum，代码可能需要根据实际题目调整）
        String code = "public class Solution {\n" +
                "    \n" +
                "    public static int twoSum(int var0,int var1){\n" +
                "        \n" +
                "    }\n" +
                "}";

        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript(
                "var editor = ace.edit(arguments[0]);" +
                        "editor.setValue(arguments[1]);",
                codeEditor, code
        );
        js.executeScript(
                "var editor = ace.edit(arguments[0]);" +
                        "editor.setValue(arguments[1]);",
                codeEditorMain, code
        );

        System.out.println("代码编写完成。");
        getScreenShot("codeWritten");

        // 点击“提交”按钮
        WebElement submitButton = wait.until(ExpectedConditions.elementToBeClickable(
                By.xpath("/html/body/div[1]/div/section/main/div[2]/div[3]/div/div/form/div[9]/div/button/span")
        ));

        submitButton.click();

        // 等待弹窗关闭并刷新页面
        wait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//button/span[text()='提交']")));
        driver.navigate().refresh();

        // 验证新题目是否添加成功
        WebElement firstQuestionTitle = wait.until(ExpectedConditions.presenceOfElementLocated(
                By.xpath("//table/tbody/tr[1]/td[2]/div")
        ));
        assert firstQuestionTitle.getText().equals(newTitle) : "添加题目失败，新题目未出现在列表中";
        System.out.println("添加题目成功，标题: " + newTitle);
        getScreenShot("testAddQuestion");
    }
    // 测试检索题目
    public void testSearchQuestion() throws IOException {
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

        // 输入搜索关键词
        WebElement searchInput = wait.until(ExpectedConditions.elementToBeClickable(
                By.xpath("/html/body/div[1]/div/section/main/div[2]/form/div[2]/div/div/div/input")
        ));
        String searchKeyword = "小王";
        searchInput.sendKeys(searchKeyword);

        // 点击“搜索”按钮
        WebElement searchButton = wait.until(ExpectedConditions.elementToBeClickable(
                By.xpath("/html/body/div[1]/div/section/main/div[2]/form/div[3]/div/button[1]")
        ));
        searchButton.click();

        // 等待搜索结果加载
        WebElement firstQuestionTitle = wait.until(ExpectedConditions.presenceOfElementLocated(
                By.xpath("/html/body/div[1]/div/section/main/div[2]/div[1]/div[1]/div[3]/div/div[1]/div/table/tbody/tr[1]/td[2]/div")
        ));

        // 验证搜索结果
        assert firstQuestionTitle.getText().contains(searchKeyword) : "检索题目失败，未找到匹配的题目";
        System.out.println("检索题目成功，找到标题包含‘" + searchKeyword + "’的题目: " + firstQuestionTitle.getText());
        getScreenShot("testSearchQuestion");

        // 重置搜索
        WebElement resetButton = wait.until(ExpectedConditions.elementToBeClickable(
                By.xpath("//button/span[text()='重置']")
        ));
        resetButton.click();
        driver.navigate().refresh();
    }
}